package com.example.day1.Filter;


import com.alibaba.fastjson.JSON;
import com.example.day1.common.BaseContent;
import com.example.day1.common.R;
import com.example.day1.entity.Employee;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebFilter(filterName = "loginCheckFilter",urlPatterns = "/*")
@Slf4j
public class LoginCheckFilter implements Filter{
    //设置路径匹配器
    public static final AntPathMatcher PATH_MATCHER=new AntPathMatcher();



    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request=(HttpServletRequest)servletRequest;
        log.info("设置过滤器拦截到请求"+request.getRequestURI());
        HttpServletResponse response=(HttpServletResponse)servletResponse;

        //1.获取本次请求的url
       String requestURL=request.getRequestURI();

        //设置不拦截路径
        String[] urls=new String[]{"/employee/login","/employee/logout"
                ,"/backend/**","/front/**",
                "/user/sendMsg","/user/login"};
        //匹配
       boolean check= check(requestURL,urls);
       //匹配成功直接放行
       if(check){
           filterChain.doFilter(request,response);
           return;
       }
       //获取是否的登录状态的session
        if(request.getSession().getAttribute("employee")!=null){
            //每次验证成功，就向这个threadlocal中添加指定的数据，而且这个数据只对当前线程有用
          Long id=  (Long)request.getSession().getAttribute("employee");
            BaseContent.setCurrentId(id);
            filterChain.doFilter(request,response);
            return;
        }
        if(request.getSession().getAttribute("user")!=null){
           Long userid= (Long)request.getSession().getAttribute("user");
           BaseContent.setCurrentId(userid);
            filterChain.doFilter(request,response);
           return;

        }

        response.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));

        log.info("用户未登录");
        return;
    }

    @Override
    public void destroy() {

    }

    //检查本次请求是否放行
    public boolean check(String requestURL,String[] urls){
        for(String url:urls){
            boolean match=PATH_MATCHER.match(url,requestURL);
            if(match){
                return true;
            }
        }
        return false;

    }
}
